package com.factory.test.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.factory.test.R;
import com.factory.test.bean.ActivityItem;
import com.factory.test.bean.TestRecord;
import com.factory.test.util.FileUtils;
import com.google.gson.Gson;

import java.io.File;
import java.util.List;

public class BaseTestActivity extends BaseActivity {

    protected String tag = "TestData";
    private static boolean automaticTesting;
    private static int currentActivityIndex = 0;

    protected static List<ActivityItem> testGroup;
    protected static int testGroupType = 1;


    protected TextView detectDec;
    protected Button success;
    protected Button ignore;
    protected Button notSupport;
    protected Button fail;

    private int oldTestResult;
    /**
     * 启动自动测试, 点了正常后自动跳到下一个界面
     * @param context
     */
    public static void startAutoTest(Context context, int index, boolean automaticTesting) {
        BaseTestActivity.currentActivityIndex = index;
        BaseTestActivity.automaticTesting = automaticTesting;

        ActivityItem item = testGroup.get(index);
        Intent intent = new Intent();
        intent.putExtra("activityInfo", item);
        intent.putExtra("testResult", item.getTestResult());
        intent.setClassName(context, item.getClassName());
        context.startActivity(intent);
    }

//    public static void startTestActivity(Context context, List<ActivityItem> list, int testGroupType, int currentActivityIndex){
//        BaseTestActivity.testGroup = list;
//        BaseTestActivity.testGroupType = testGroupType;
//        BaseTestActivity.currentActivityIndex = currentActivityIndex;
//        BaseTestActivity.automaticTesting = true;
//        ActivityItem item = list.get(currentActivityIndex);
//        Intent intent = new Intent();
//        intent.putExtra("activityInfo", item);
//        intent.setClassName(context, item.getClassName());
//        context.startActivity(intent);
//    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        ActivityItem activityInfo = (ActivityItem) intent.getSerializableExtra("activityInfo");
        if(activityInfo != null){
            actionBar.setTitle(activityInfo.getMenuMenu());
        }

        int type = intent.getIntExtra("testGroupType", -1);
        if(type != -1){
            testGroupType = type;
        }

        int index = intent.getIntExtra("currentActivityIndex", -1);
        if(index != -1){
            currentActivityIndex = index;
        }

        oldTestResult = intent.getIntExtra("testResult", 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        View rootView  = getWindow().getDecorView().findViewById(android.R.id.content);
        success = rootView.findViewById(R.id.success);
        ignore = rootView.findViewById(R.id.ignore);
        fail = rootView.findViewById(R.id.fail);
        notSupport = rootView.findViewById(R.id.not_support);
        if(success != null) {
            success.setOnClickListener(onClickListener);
            ignore.setOnClickListener(onClickListener);
            fail.setOnClickListener(onClickListener);
            notSupport.setOnClickListener(onClickListener);
        }
    }

    private static final int MIN_CLICK_DELAY_TIME = 500;    //两个点击最小间隔
    private static long lastClickTime = 0;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            long curTime = System.currentTimeMillis();
            if (curTime - lastClickTime > MIN_CLICK_DELAY_TIME) { //只有大于才会走逻辑
                if (v == success) {
                    onOK();

                } else if (v == ignore) {
                    onIgnore();

                } else if (v == notSupport) {
                    onNotSupport();

                } else if (v == fail) {
                    onNG();
                }
            }else{
                Log.i(tag, "大胸弟, 你点击过快啦: " + (curTime - lastClickTime));
            }
        }
    };

    public void setDesc(String desc){
        if(detectDec == null){
            View rootView  = getWindow().getDecorView().findViewById(android.R.id.content);
            detectDec = rootView.findViewById(R.id.detect_dec);
        }

        if(detectDec != null) {
            detectDec.setText(desc);
        }
    }

    private int testResult;     //0未测试，1成功， 2失败
    public void onOK(){
        testResult = 1;
        saveTestData();
    }

    public void onIgnore(){
        testResult = oldTestResult;
        saveTestData();
    }

    public void onNotSupport(){
        testResult = 3;
        saveTestData();
    }

    public void onNG(){
        testResult = 2;
        saveTestData();
    }



    /**
     * 保存测试记录
     */
    private void saveTestData(){
        try {
            TestRecord testRecord = new TestRecord();
            testRecord.setVersionCode(myApplication.getAppVersionCode());
            testRecord.setVersionName(myApplication.getAppVersionName());
            testRecord.setChannel(myApplication.getChannelName());
            testGroup.get(currentActivityIndex).setTestResult(testResult);
            testRecord.setInfoList(testGroup);
            Gson gson = new Gson();
            String json = gson.toJson(testRecord);

            String filePath = getExternalFilesDir(null) + "/Test" + testGroupType + ".json";
            FileUtils.writeFile(filePath, json);

            if(testResult == 2){    //异常了不能往下走了
                finish();
                return;
            }

            if(automaticTesting){
                currentActivityIndex += 1;
                if(currentActivityIndex == testGroup.size()){   //到最后一项, 结束
                    finish();
                    return;
                }

                ActivityItem item = testGroup.get(currentActivityIndex);
                if(item.getClassName() == null){                //下一项为空, 结束
                    finish();
                    return;
                }

                if(item.getTestResult() != 0){                  //如果下一个已测试过则跳出
                    finish();
                    return;
                }

                Intent intent = new Intent();
                intent.putExtra("activityInfo", item);
                intent.setClassName(context, item.getClassName());
                context.startActivity(intent);                  //跳到下一项测试
            }


            finish();
        } catch (Exception e) {
            showError("测试数据保存失败");
            Log.e("ytTest", "save data fail", e);
        }
    }


    protected boolean deleteTestData(){
        String filePath = getExternalFilesDir(null) + "/Test" + testGroupType + ".json";
        File file = new File(filePath);
        return file.delete();
    }

    protected String readTestData(){
        String filePath = getExternalFilesDir(null) + "/Test" + testGroupType + ".json";
        return FileUtils.readFile(filePath);
    }

}
